package yxk.task;

import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.api.MessageHandler;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import javax.xml.crypto.Data;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Map;
import java.util.logging.Filter;

/**
 * 计算在职日期
 */
public class CountBeOnJobDate extends AbstractTask{
    @Override
    public MessageHandler getMessageHandle() {
        return super.getMessageHandle();
    }

    /**
     * 实现步骤：
     *          1.获取所有人员信息
     *          2.将人员最后任职时间获取出来
     *          3.根据当日时间减去最后调动日期，获取当前时间
     * @param requestContext
     * @param map
     * @throws KDException
     */
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        //1.获取所有人员信息
        QFilter personFilter=new QFilter("iscurrentversion", QCP.equals,'1');
        DataSet personRows = QueryServiceHelper.queryDataSet(this.getClass().getName(), "hrpi_person", "id,number", personFilter.toArray(), null);
        for (Row row:personRows){
            //2.将人员最后任职时间获取出来
            QFilter qFilter = new QFilter("person.number", QCP.equals,row.getString("number"));
            qFilter = qFilter.and(new QFilter("datastatus",QCP.equals,"1"));
            DataSet rows = QueryServiceHelper.queryDataSet(this.getClass().getName(), "hrpi_empposorgrel", "startdate,enddate", qFilter.toArray(), "enddate desc");
            //取第一条数据
            Date nowDate = new Date();
            DecimalFormat df=new DecimalFormat("0.00");
            n:for (Row empposorgrelRow:rows){
                Date startdate = empposorgrelRow.getDate("startdate");
                if(empposorgrelRow.getDate("enddate")!=null&&(empposorgrelRow.getDate("enddate").getTime()<nowDate.getTime())){
                    nowDate = empposorgrelRow.getDate("enddate");
                }
                long time = nowDate.getTime() - startdate.getTime();
                String format = df.format((float) time/ 31536000000L);
                DynamicObject[] hrpi_perserlens = BusinessDataServiceHelper.load("hrpi_perserlen", "id,nwg5_textfield", qFilter.toArray());
                for (int i = 0; i < hrpi_perserlens.length; i++) {
                    hrpi_perserlens[i].set("nwg5_textfield",format+"年");
                }
                SaveServiceHelper.save(hrpi_perserlens);
                break n;
            }

        }
    }
}
